package aar.test.tessocr;


import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.OpenCVLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.EventMessage.MessageEvent;
import aar.test.tessocr.adapter.AppointmentOrderAdapter;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.AppointmentOrderModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.OcrOpenCabModel;
import aar.test.tessocr.tessOcrUtil.ListViewForScrollView;
import aar.test.tessocr.tessOcrUtil.TesseractUtil;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.LogUtils;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.UnzipAssets;
import aar.test.tessocr.utils.Urls;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CaptureFragment;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.EventMessage.MessageEvent.ORDERID;
import static aar.test.tessocr.EventMessage.MessageEvent.SEARCH_CABINET;
import static aar.test.tessocr.Login1Activity.JSON;

public class OpenCabActivity extends BaseActivity {

    private Context mContext;

    private DisplayMetrics dm;

    private LinearLayout left_layout;

    private TextView title_info;

    private TextView scan_open_cab;

    private TextView open_conf;

    private String text;

    private FrameLayout fl_zxing_container;
    private EditText san_order_id;
    private Boolean isFromReturnOrderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFromReturnOrderId = getIntent().getBooleanExtra("isFromReturnOrderId", false);
        mContext = this;
        setContentView(R.layout.activity_open_cab);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        iniLoadOpenCV();


        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        }else {

            unZipAssset();
        }


    }

    private void iniLoadOpenCV() {
        boolean success = OpenCVLoader.initDebug();
        if (success) {
            Log.e("MainActivity", "OpenCV Library loaded...");
        } else {
            Toast.makeText(this.getApplicationContext(), "could not load opencv lib...", Toast.LENGTH_SHORT).show();
        }
    }


    private void unZipAssset() {

        prepareSdPath();

        prepareSdPath2();

        try {

            File file = new File(TesseractUtil.TESSBASE_PATH_DOWN);

            File file2 = new File(TesseractUtil.TESSBASE_PATH_DOWN + "/eng.traineddata");

            if (!file.exists() || (file.exists() && !file2.exists())) {
                new Thread() {
                    public void run() {
                        //在新线程中以同名覆盖方式解压
                        UnzipAssets.unZip(OpenCabActivity.this, ConstantPara.UN_ZIP_ASSET_NAME, TesseractUtil.TESSBASE_PATH, true);
                    }
                }.start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath() {

        try {

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRootThumbnail = new File(TesseractUtil.TESSBASE_PATH);
                if (!sPathRootThumbnail.exists()) {
                    sPathRootThumbnail.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath2() {

        String RootFilePath = Environment.getExternalStorageDirectory() + "/DCIM/";

        String sSubDir = "normal";
//        String RootFilePath=  Environment.getExternalStorageDirectory() + "/Download/";

        try {


            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRoot = new File(RootFilePath);
                if (!sPathRoot.exists()) {
                    sPathRoot.mkdirs();
                }
                File sPathVid = new File(RootFilePath + sSubDir);
                LogUtils.e("MainActivity", "sPathVid.exists()==" + sPathVid.exists());
                if (!sPathVid.exists()) {
                    sPathVid.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void initView() {

        CaptureFragment captureFragment =CaptureFragment.newInstance(1);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
        captureFragment.setCameraInitCallBack(new CaptureFragment.CameraInitCallBack() {
            @Override
            public void callBack(Exception e) {
                if (e == null) {

                } else {
                    Log.e("TAG", "callBack: ", e);
                }
            }
        });


        left_layout = findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        fl_zxing_container = findViewById(R.id.fl_zxing_container);

        if (isFromReturnOrderId) {
            TextView title = findViewById(R.id.title);
            title.setText("扫码回填");
            ScrollView info_scroll_layout = findViewById(R.id.info_scroll_layout);
            info_scroll_layout.setVisibility(View.GONE);
        } else {
            san_order_id = findViewById(R.id.san_order_id);

            scan_open_cab = findViewById(R.id.scan_open_cab);
            scan_open_cab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    scanOpenCab();
                }
            });


            open_conf = findViewById(R.id.open_conf);
            open_conf.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gridConfirem();
                }
            });
        }
    }





    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(OpenCabActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(OpenCabActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };








    @Override
    protected void onDestroy() {
        super.onDestroy();

        OkGo.getInstance().cancelTag(this);
    }


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result, final int type) {

//            if (type == 1) {
//                Toast.makeText(AppointmentOrderActivity.this, "bar      " + result, Toast.LENGTH_LONG).show();
//            } else if (type == 2) {
//                Toast.makeText(AppointmentOrderActivity.this, "phone       " + result, Toast.LENGTH_LONG).show();
//            }

            final String res = result;
            if (!TextUtils.isEmpty(res)) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (type == 1) {
                            if (isFromReturnOrderId) {
                                EventBus.getDefault().post(new MessageEvent(ORDERID, res));
                                finish();
                            } else {
                                san_order_id.setText(res);
                                scanOpenCab();
                            }

                        } else if (type == 2) {


                        }


                    }
                });
            }


        }

        @Override
        public void onAnalyzeFailed() {

            Toast.makeText(OpenCabActivity.this, "没有识别到信息", Toast.LENGTH_SHORT).show();
        }
    };



    OcrOpenCabModel ocrOpenCabModel;

    private void scanOpenCab() {
        if (!PrefUtils.getBoolean(this, "cabinetLoginFlag", false)) {
            Toast.makeText(mContext,"没有柜子信息，请扫描登录",Toast.LENGTH_SHORT).show();
            return;
        }

        String mm=san_order_id.getText().toString();

        if(TextUtils.isEmpty(mm)){
            Toast.makeText(mContext,"没有运单号，请扫描",Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, Object> map = new HashMap<>();

        map.put("cabinetId",PrefUtils.getString(this, "cabinetId", "0"));
        map.put("express", mm );

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_YUYUE_ORC)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<String>(OpenCabActivity.this) {
                    @Override
                    public void onSuccess(Response<String> response) {

                        /*if(null!=response.body().data){
                            ocrOpenCabModel=response.body().data;
                        }*/

                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg = jsonObject.getString("msg");
                                    Toast.makeText(OpenCabActivity.this, msg, Toast.LENGTH_SHORT).show();
                                } else if (TextUtils.equals(code, "100")) {
                                    String msg = jsonObject.getString("msg");
                                    Gson gg = new Gson();
                                    ocrOpenCabModel=gg.fromJson(jsonObject.getString("data"),OcrOpenCabModel.class);
                                    Toast.makeText(OpenCabActivity.this, msg, Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        Toast.makeText(getApplicationContext(),"无此快递单!",Toast.LENGTH_SHORT).show();
                    }
                });


    }




    private void gridConfirem() {

        if(null==ocrOpenCabModel||null==ocrOpenCabModel.getCabinetgridid()){
            Toast.makeText(OpenCabActivity.this, "没有柜子信息，请先开柜再确认！", Toast.LENGTH_SHORT).show();
            return;
        }


//        if (TextUtils.isEmpty(BaseApplication.getIntance().getLoginBean().getId())) {
//            Toast.makeText(mContext, "管理员id为空", Toast.LENGTH_LONG).show();
//            return;
//
//        }
        String mm=san_order_id.getText().toString();

        if(TextUtils.isEmpty(mm)){
            Toast.makeText(mContext, "请输入运单号", Toast.LENGTH_SHORT).show();
            return;
        }

//        if(TextUtils.isEmpty(mList.get(pos).getPhone())){
//            Toast.makeText(mContext, "请输入电话号", Toast.LENGTH_LONG).show();
//            return;
//        }





        Map<String, Object> map = new HashMap<>();
        map.put("cabinetGridId",ocrOpenCabModel.getCabinetgridid());
        map.put("express", mm);
        map.put("type", "1");
//        map.put("phone", BaseApplication.getIntance().getLoginBean().);
//        map.put("adminid", BaseApplication.getIntance().getLoginBean().getId());

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse>post(Urls.URL_XIANCHANG_CONFIRM)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(OpenCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {


                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);
                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_SHORT).show();
                            san_order_id.setText("");
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {

                        Log.e("MainActivity", "onError---------------------");
                        if(null!=response&&null!=response.body()&&null!=response.body().msg){
                            Toast.makeText(getApplicationContext(),response.body().msg,Toast.LENGTH_SHORT).show();
                        }

                    }
                });


    }





}
